package smartcounters.androidclient;

import java.util.LinkedList;

import smartcounters.androidclient.WebServices.InformationReaderWebServiceClient;
import smartcounters.androidclient.WebServices.InformationUpdaterWebServiceClient;
import smartcounters.androidclient.WebServices.OnResultReceiver;
import smartcounters.androidclient.model.AccountInfo;
import smartcounters.androidclient.model.Configuration;
import smartcounters.androidclient.model.UserInfo;
import smartcounters.androidclient.model.eOperationsEnum;
import smartcounters.androidclient.model.eUserPermissions;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.app.Activity;

public class SendFaultActivity extends Activity implements OnClickListener, OnResultReceiver {
	
	private String[] m_AccountsAssociatedWithArray;
	private int[] m_AccountIDsAssociatedWithArray;
	private AccountInfo[] m_AccountInfos;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send_fault_layout);
        
        Button sendFaultButton = (Button)findViewById(R.id.buttonSendFault);
        sendFaultButton.setOnClickListener(this);
        sendFaultButton.setEnabled(false);
        
        InformationReaderWebServiceClient readerClient = new InformationReaderWebServiceClient(Configuration.getInstance().getServerAddress());
		readerClient.RegisterResultReceiver(this);
		readerClient.GetAllAccounts(Configuration.getInstance().getAdminAuthenticatedCredentials());
    }

	public void onClick(View arg0) {
		if (arg0.getId() == R.id.buttonSendFault){
			Spinner accountIDSpinner = (Spinner)findViewById(R.id.sendFaultAccountIDSpinner);
			EditText descriptionEditText = (EditText)findViewById(R.id.sendFaultDescriptionEditText);
			int accountID = m_AccountIDsAssociatedWithArray[accountIDSpinner.getSelectedItemPosition()];
			
			InformationUpdaterWebServiceClient updaterClient = new InformationUpdaterWebServiceClient(Configuration.getInstance().getServerAddress());
			updaterClient.RegisterResultReceiver(this);
			updaterClient.CreateFault(Configuration.getInstance().getUserCredentials(), accountID, descriptionEditText.getText().toString());
		}
	}

	public void ReceiveResult(Message i_Msg) {
		if (eOperationsEnum.values()[i_Msg.what] == eOperationsEnum.CreateFault){
        	TextView messageTextView = (TextView)findViewById(R.id.sendFaultMessageTextView);
			messageTextView.setText("The fault was created.");
        }
		else if (eOperationsEnum.values()[i_Msg.what] == eOperationsEnum.GetUserInformationByID){
			UserInfo userInfo = (UserInfo)i_Msg.obj;
			LinkedList<Integer> accountIDs = userInfo.getAccountsAssociatedWith();
			m_AccountsAssociatedWithArray = new String[accountIDs.size()];
			m_AccountIDsAssociatedWithArray = new int[accountIDs.size()];
			
			int i = 0;
			
			for (int accountID : accountIDs){
				AccountInfo account = findAccount(accountID);
				
				if (account != null){
					String text = account.getApartment() == -1 ? account.getCountry() + ", " + account.getCity() + ", " + account.getStreet() + ", " + String.valueOf(account.getHouse()) :
		        		account.getCountry() + ", " + account.getCity() + ", " + account.getStreet() + ", " + String.valueOf(account.getHouse()) + " / " + String.valueOf(account.getApartment());
					
					m_AccountsAssociatedWithArray[i] = text;
					m_AccountIDsAssociatedWithArray[i] = m_AccountInfos[i].getAccountID();
				}
				
				i++;
			}
			
			Spinner accountIDSpinner = (Spinner)findViewById(R.id.sendFaultAccountIDSpinner);
			
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m_AccountsAssociatedWithArray);
			accountIDSpinner.setAdapter(adapter);
	        
			Button sendFaultButton = (Button)findViewById(R.id.buttonSendFault);
	        sendFaultButton.setEnabled(true);
        }
		else if (eOperationsEnum.values()[i_Msg.what] == eOperationsEnum.GetAllAccounts){
			m_AccountInfos = (AccountInfo[])i_Msg.obj;
			
			if (Configuration.getInstance().getLoggedInUser().getUserPermissions().contains(eUserPermissions.All)){
	        	// If the user is an administrator, let him create a fault with any account.
	        	
				m_AccountsAssociatedWithArray = new String[m_AccountInfos.length];
				m_AccountIDsAssociatedWithArray = new int[m_AccountInfos.length];
				
				for (int i = 0; i < m_AccountInfos.length; i++){
					String text = m_AccountInfos[i].getApartment() == -1 ? m_AccountInfos[i].getCountry() + ", " + m_AccountInfos[i].getCity() + ", " + m_AccountInfos[i].getStreet() + ", " + String.valueOf(m_AccountInfos[i].getHouse()) :
						m_AccountInfos[i].getCountry() + ", " + m_AccountInfos[i].getCity() + ", " + m_AccountInfos[i].getStreet() + ", " + String.valueOf(m_AccountInfos[i].getHouse()) + " / " + String.valueOf(m_AccountInfos[i].getApartment());
					
					m_AccountsAssociatedWithArray[i] = text;
					m_AccountIDsAssociatedWithArray[i] = m_AccountInfos[i].getAccountID();
				}
				
				Spinner accountIDSpinner = (Spinner)findViewById(R.id.sendFaultAccountIDSpinner);
				
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m_AccountsAssociatedWithArray);
				accountIDSpinner.setAdapter(adapter);
		        
				Button sendFaultButton = (Button)findViewById(R.id.buttonSendFault);
		        sendFaultButton.setEnabled(true);
	        }
	        else{
	        	// If the user is a simple user, let him only create faults with accounts associated with him.
	        	
	        	InformationReaderWebServiceClient readerClient = new InformationReaderWebServiceClient(Configuration.getInstance().getServerAddress());
	    		readerClient.RegisterResultReceiver(this);
	    		readerClient.GetUserInformationByID(Configuration.getInstance().getUserCredentials(), Configuration.getInstance().getUserCredentials().getID());
	        }
        }
	}
	
	private AccountInfo findAccount(int i_AccountID){
		for (int i = 0; i < m_AccountInfos.length; i++){
			if (m_AccountInfos[i].getAccountID() == i_AccountID){
				return m_AccountInfos[i];
			}
		}
		
		return null;
	}
}
